package com.cloud.demo.sgip;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloud.demo.utils.ByteConvert;


public class FDecoder extends CumulativeProtocolDecoder {
	private static Logger log = LoggerFactory.getLogger(FDecoder.class);

	@Override
	protected boolean doDecode(IoSession session, IoBuffer ioBuffer, ProtocolDecoderOutput out) throws Exception {
//		log.debug("开始解码");
		if (ioBuffer.remaining() < 20){
			log.debug("开始解码remaining小于20");
			return false;
		}
		if (ioBuffer.remaining() > 20) {
			ioBuffer.mark(); //做标记
	        byte[] headBytes = new byte[SgipCommand.MsgHeaderLength];
	        
	        ioBuffer.get(headBytes);//读取前20字节   
			byte totalLenBytes[]=new byte[SgipCommand.MsgTotalLength];
			byte commandIdBytes[]=new byte[SgipCommand.MsgCommandId];
			byte sequenceIdBytes[]=new byte[SgipCommand.MsgSequenceId];
			System.arraycopy(headBytes, 0, totalLenBytes, 0, 4);
			System.arraycopy(headBytes, 4, commandIdBytes, 0, 4);
			System.arraycopy(headBytes, 8, sequenceIdBytes, 0, 12);
	 		int length = ByteConvert.bytesToInt(totalLenBytes);
	 		int bodyLen=length-20;
	 		int reLen=ioBuffer.remaining();
	 		log.debug("length:"+length+",bodyLen:"+bodyLen+",reLen:"+reLen);
	 		if(ioBuffer.remaining()<bodyLen){//如果消息内容不够，则重置，相当于不读取size  
	 			ioBuffer.reset();  
                return false;//接收新数据，以拼凑成完整数据  
            } else{ 
            	ioBuffer.reset();//重置恢复position位置到操作前
            	byte[] packArr = new byte[length];
            	ioBuffer.get(packArr, 0 , length);
                out.write(packArr);

            	if(ioBuffer.remaining() > 0){
            		 //如果读取内容后还粘了包，就让父类再给一次，进行下一次解析  
            		return true;  
            	}   
            }
		}
		return false;// 处理成功，让父类进行接收下个包
	}
}